package org.example.servletpractice.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "UploadServlet", value = "/uploadServlet")
public class UploadServlet extends HttpServlet {

    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //检查是否是文件上传
        if(!ServletFileUpload.isMultipartContent(req)){
            PrintWriter writer = resp.getWriter();
            writer.println("当前只接受文件上传");
            writer.flush();
            return;
        }
        //配置上传参数
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        //设置临时存储目录
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //设置文件最大上传值
        fileUpload.setFileSizeMax(MAX_FILE_SIZE);
        //设置最大请求值
        fileUpload.setSizeMax(MAX_REQUEST_SIZE);
        //中文处理
        fileUpload.setHeaderEncoding("UTF-8");
        //文件存储路径
        String path = "D:\\tmp";

        try {
            //解析请求的内容提取文件数据
            List<FileItem> fileItems = fileUpload.parseRequest(req);

            if(fileItems !=null && !fileItems.isEmpty()){
                //遍历表单数据
                for (FileItem fileItem : fileItems) {
                    //处理不在表单中的字段
                    if(!fileItem.isFormField()){
                        String fileName = new File(fileItem.getName()).getName();
                        String filePath = path+File.separator+fileName;
                        File file = new File(filePath);
                        //在控制台输出文件上传路径
                        System.out.println(filePath);
                        fileItem.write(file);
                        req.setAttribute("message","上传文件成功");
                    }
                }
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
            req.setAttribute("message","错误信息"+e.getMessage());
        }
        req.getServletContext().getRequestDispatcher("/message.jsp").forward(req,resp);
    }
}
